/**
 * 
 */
package org.compiere.report;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.adempiere.exceptions.AdempiereException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPartner;
import org.compiere.model.MFI_C_PaymentLine;
import org.compiere.model.MOrg;
import org.compiere.model.MPayment;
import org.compiere.process.ProcessInfo;
import org.compiere.process.SvrProcess;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.utils.fwMoney;

import extend.org.compiere.utils.Util;

/**
 * @author A.Kulantayev
 *
 */
public class FI_PaymentPrintForm extends SvrProcess {
	/** Current context */
	private Properties m_ctx;
	private ProcessInfo pi;
	/**Current Record_ID */
	int p_C_Payment_ID = 0;
	/**Out file */
	String ResultPath;
	@Override
	protected void prepare() {
		log.info("");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		p_C_Payment_ID = pi.getRecord_ID();
		
		if(p_C_Payment_ID==0){
			log.log(Level.SEVERE, "Error initializing the parameter C_Payment_ID: p_C_Payment_ID ="+p_C_Payment_ID);
			throw new AdempiereException(Msg.translate(m_ctx,"Error initializing the parameter C_Payment_ID. Parameter does not exists"));
		}
	}
	@Override
	protected String doIt() throws Exception {
		MPayment payment = new MPayment(m_ctx, p_C_Payment_ID, get_TrxName());
		if(payment.getC_DocType_ID()==1000058 || payment.getC_DocType_ID()==1000059){
			//File path
			ResultPath = Util.getResultPath(payment.getC_DocType().getName()+" "+payment.getDocumentNo()
					, (new String(payment.getC_DocType().getName()+" "+payment.getDocumentNo()).length())+1);
			// 
			  MAttachmentEntry entry = Util. getAttachment(pi, m_ctx, ResultPath);
			if (entry == null)
				throw new AdempiereException(Msg.translate(m_ctx,"NotFoundTemplate"));
			
			XSSFWorkbook wb = new XSSFWorkbook(entry.getInputStream());
			XSSFSheet sheet = wb.getSheetAt(0);
			Row R = null;
			//TODO Title 
			sheet.getRow(0).getCell(0).setCellValue(new MOrg(m_ctx, payment.getAD_Org_ID(), get_TrxName()).getDescription());
			sheet.getRow(2).getCell(0).setCellValue("Ведомость № "+payment.getDocumentNo()+" от "
													+new SimpleDateFormat("dd").format(payment.getDateAcct())
													+" "+new SimpleDateFormat("MMMMM").format(payment.getDateAcct())
													+" "+new SimpleDateFormat("yyyy").format(payment.getDateAcct()));
			if(payment.getC_DocType_ID()==1000058){
				sheet.getRow(3).getCell(0).setCellValue("на перечисление денежных средств в подотчет в "+payment.getC_BPartner().getName());
			}
			if(payment.getC_DocType_ID()==1000059){
				sheet.getRow(3).getCell(0).setCellValue("на перечисление заработной платы в "+payment.getC_BPartner().getName());
			}
			//
			int rowNo = 7;
			MFI_C_PaymentLine[] m_lines = null;
			List<MFI_C_PaymentLine> list = MFI_C_PaymentLine.getMFI_C_PaymentLines(log, m_ctx, payment.getC_Payment_ID());
			m_lines = list.toArray(new MFI_C_PaymentLine[list.size()]);
			int i = 1;
			for(MFI_C_PaymentLine line : m_lines){
				sheet.shiftRows(rowNo, rowNo+10, 1);
				R = sheet.createRow(rowNo);
				R.createCell(0).setCellValue(String.valueOf(i));
				R.getCell(0).setCellStyle(sheet.getRow(0).getCell(7).getCellStyle());
				R.createCell(1).setCellValue(line.getC_BPartner().getName());
				R.getCell(1).setCellStyle(sheet.getRow(0).getCell(8).getCellStyle());
				R.createCell(2).setCellValue(line.getC_BPartner().getFI_TIN());
				R.getCell(2).setCellStyle(sheet.getRow(0).getCell(9).getCellStyle());
				//
				String bankaccount = DB.getSQLValueString(get_TrxName(), "SELECT AccountNo FROM C_BP_BankAccount WHERE C_BPartner_ID = ?"
																		, line.getC_BPartner_ID());
				R.createCell(3).setCellValue(bankaccount);
				R.getCell(3).setCellStyle(sheet.getRow(0).getCell(10).getCellStyle());
				//
				R.createCell(4).setCellValue(line.getAmount().doubleValue());
				R.getCell(4).setCellStyle(sheet.getRow(0).getCell(11).getCellStyle());
				i++;rowNo++;
			}
			//sheet.getRow(rowNo).getCell(4).setCellFormula("SUM(E8:E"+rowNo+")");
			//Total
			sheet.getRow(rowNo).getCell(4).setCellValue(payment.getPayAmt().doubleValue());
			double payAmt = 0;
			if(payment.getPayAmt().doubleValue()<0)
				payAmt = payment.getPayAmt().negate().doubleValue();
			else
				payAmt = payment.getPayAmt().doubleValue();
			//sum words
			sheet.getRow(rowNo+1).getCell(0).setCellValue(new fwMoney(payAmt).num2str().substring(0, 1).toUpperCase()+
					new fwMoney(payAmt).num2str().substring(1, new fwMoney(payAmt).num2str().length()));
			//Заместитель Председателя Правления
			MBPartner chiefSignature = new MBPartner(m_ctx, payment.getFI_ChiefSignature_ID(), get_TrxName());
			sheet.getRow(rowNo+3).getCell(5).setCellValue(chiefSignature.getLastName()+" "+chiefSignature.getFirstName().substring(0, 1)
							+". "+chiefSignature.getMiddleName().substring(0, 1)+".");
			//Главный бухгалтер
			MBPartner  chiefAccountantSignature = new MBPartner(m_ctx, payment.getFI_ChiefAccountantSignature_ID(), get_TrxName());
			sheet.getRow(rowNo+5).getCell(5).setCellValue(chiefAccountantSignature.getLastName()+" "
							+chiefAccountantSignature.getFirstName().substring(0, 1)+". "+chiefAccountantSignature.getMiddleName().substring(0, 1)+".");
			
			//delete temp styles
			R = sheet.getRow(0);
			for(int j = 7; j<13; j++){
				R.getCell(j).setCellStyle(sheet.getRow(0).getCell(0).getCellStyle());
			}
			//
			// Write the output to a file
			FileOutputStream fileOut = new FileOutputStream(ResultPath);
			wb.write(fileOut);
			fileOut.close();
			// Open the file with the application associated
			Util.launchFile(new File(ResultPath));
			return Msg.translate(m_ctx, "Success");
		}
		else{
			return Msg.translate(m_ctx, "Error")+" Неправильный тип документа";
		}
	}

}
